from common.errorcode import Errorquery
from models import Cabinet, Lattice, Box


def get_cabinets_list():
    try:
        object_list = []
        cabinets = Cabinet.objects.all()
        for cabinet in cabinets:
            object = {}
            object["id"] = cabinet.id
            object["admin"] = cabinet.admin.realname
            object["material"] = cabinet.material
            object["address"] = cabinet.storage_location
            object["code"] = cabinet.code
            object["remark"] = cabinet.remark
            object["fileNum"] = Lattice.objects.filter(cabinet=cabinet).count()
            object_list.append(object)
        return object_list
    except Exception as e:
        return Errorquery(e)


def get_cabinet_detail(code):
    try:
        cabinets =  Cabinet.objects.filter(id=code)
        for cabinet in cabinets:
            return cabinet
        return Errorquery("null")
    except Exception as e:
        return Errorquery(e)


def get_lattices_list(cabinet):
    try:
        object_list = []
        lattices = Lattice.objects.filter(cabinet=cabinet)
        for lattice in lattices:
            object = {}
            object["id"] = lattice.id
            object["code"] = lattice.code
            object["boxes"] = get_boxes_list(lattice)
            object_list.append(object)
        return object_list
    except Exception as e:
        return Errorquery(e)


def get_box_detail(code):
    try:
        return list(Box.objects.filter(code=code).values())
    except Exception as e:
        return Errorquery(e)


def get_boxes_list(lattice):
    try:
        return list(Box.objects.filter(lattice=lattice).values())
    except Exception as e:
        return Errorquery(e)
